package com.eqs.enterprisequestionnaire.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eqs.enterprisequestionnaire.mapper.QuestionMapper;
import com.eqs.enterprisequestionnaire.mapper.ResponseMapper;
import com.eqs.enterprisequestionnaire.mapper.ResponseVoMapper;
import com.eqs.enterprisequestionnaire.model.pojo.Response;
import com.eqs.enterprisequestionnaire.model.vo.ResponseVo;
import com.eqs.enterprisequestionnaire.service.ResponseVoService;
import com.eqs.enterprisequestionnaire.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Service
public class ResponseVoServiceImpl extends ServiceImpl<ResponseVoMapper, ResponseVo> implements ResponseVoService {
    @Autowired
    ResponseVoMapper responseVoMapper;
    @Autowired
    ResponseMapper responseMapper;
    @Autowired
    TimeService timeService;

    public List<ResponseVo> getAllResponseVoByQuestionnaireId(Integer questionnaireId) {
        QueryWrapper<Response> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id", questionnaireId);
        List<Response> responses = responseMapper.selectList(queryWrapper);
        List<ResponseVo> responsesVo = new ArrayList<>();
        for (Response r : responses) {
            if (r.getSubmittedTime() != null) {
                Double finishedTime = getFinishedTime(r);
                Double averageFinishedTime = timeService.averageFinishedTime(questionnaireId);

                ResponseVo responseVo = new ResponseVo();
                responseVo.setQuestionnaireId(questionnaireId);
                responseVo.setSubmittedTime(r.getSubmittedTime());
                responseVo.setFinishedTime(finishedTime);
                responseVo.setAverageFinishedTime(averageFinishedTime);

                responsesVo.add(responseVo);
            }
        }
        return responsesVo;
    }

    public Double getFinishedTime(Response response) {
        Duration duration = Duration.between(response.getStartTime(), response.getSubmittedTime());
        return (double) duration.toMinutes();
    }
}
